<template>
  <div id="app">
    <el-steps :active="step" align-center finish-status="success">
      <el-step title="第一步"></el-step>
      <el-step title="第二步"></el-step>
      <el-step title="第三步"></el-step>
      <el-step title="第四步"></el-step>
    </el-steps>
    <section class="button-control">
      <label for="leftFile">上传左侧表格文件</label>
      <label for="rightFile">上传右侧表格文件</label>
      <label @click="analysis">开始分析</label>
      <label @click="exportExcel">导出EXCEL</label>
    </section>
    <section class="form">
      <section class="left">
        <input
          type="file"
          id="leftFile"
          name="leftFile"
          ref="leftUpload"
          accept=".xls, .xlsx"
          class="inputfile"
          @change="readExcel($event, 'left')"
        >
        <el-table :data="leftData" stripe border height="70vh">
          <el-table-column :label="leftTitle" align="center">
            <el-table-column
              v-for="(item, index) in leftDataName"
              :prop="item"
              :label="item"
              align="center"
              :key="index"
            ></el-table-column>
          </el-table-column>
        </el-table>
      </section>
      <section class="right">
        <input
          type="file"
          id="rightFile"
          name="rightFile"
          ref="leftUpload"
          accept=".xls, .xlsx"
          class="inputfile"
          @change="readExcel($event, 'right')"
        >
        <el-table id="output-table" :data="rightData" stripe border height="70vh">
          <el-table-column :label="rightTitle" align="center">
            <el-table-column
              v-for="(item, index) in rightDataName"
              :prop="item"
              :label="item"
              align="center"
              :key="index"
            ></el-table-column>
          </el-table-column>
        </el-table>
      </section>
    </section>
  </div>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
import { allSettled } from "q";

export default {
  name: "app",
  data() {
    return {
      leftData: [],
      rightData: [],
      leftTitle: "左侧表格：例如1月销售数据表",
      rightTitle: "右侧表格：例如全年销售数据表",
      step: 0
    };
  },
  computed: {
    leftDataName() {
      return this.leftData.length > 0 ? Object.keys(this.leftData[0]) : [];
    },
    rightDataName() {
      return this.rightData.length > 0 ? Object.keys(this.rightData[0]) : [];
    }
  },
  methods: {
    async analysis() {
      let leftStr, rightStr, outputStr;
      await this.$prompt("请输入左侧ID字段", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "默认为存货编码，直接点击确定即可"
      }).then(({ value }) => {
        if (!value) {
          value = "存货编码";
        }
        this.$message({
          type: "success",
          message: "左侧ID字段是: " + value
        });
        leftStr = value;
      });
      await this.$prompt("请输入右侧ID字段", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "默认为工厂型号，直接点击确定即可"
      }).then(({ value }) => {
        if (!value) {
          value = "工厂型号";
        }
        this.$message({
          type: "success",
          message: "右侧ID字段是: " + value
        });
        rightStr = value;
      });
      await this.$prompt("请输入左侧输出字段", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "默认为合计，直接点击确定即可"
      }).then(({ value }) => {
        if (!value) {
          value = "合计";
        }
        this.$message({
          type: "success",
          message: "左侧输出字段是: " + value
        });
        outputStr = value;
      });

      this.rightData.forEach(item => {
        let obj = _.find(this.leftData, o => {
          return o[leftStr] === item[rightStr];
        });
        item["新增项"] = obj ? obj[outputStr] : 0;
      });
      this.$set(this.rightData, this.rightData);
      this.step = 3
    },

    exportExcel() {
      /* generate workbook object from table */
      var wb = XLSX.utils.table_to_book(
        document.querySelector("#output-table")
      );
      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "sheetjs.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      this.step = 4
      return wbout;
    },

    readExcel(e, method) {
      //表格导入
      var that = this;
      const files = e.target.files;

      if (files.length <= 0) {
        //如果没有文件名
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$Message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }

      const fileReader = new FileReader();
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: "binary"
          });
          const wsname = workbook.SheetNames[0]; //取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容

          this[`${method}Title`] = files[0].name.split(".xl")[0];
          this[`${method}Data`] = ws;

          this.step = method === 'left' ? 1 : 2

          // this.$refs.upload.value = '';
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    }
  }
};
</script>

<style>

* {
  margin: 0;
  padding: 0;
}

html {
  background: #649173;  /* fallback for old browsers */
  background: -webkit-linear-gradient(to right, #DBD5A4, #649173);  /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to right, #DBD5A4, #649173); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}

#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  margin: 40px 20px;
}
</style>

<style scoped lang="stylus">
.button-control {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;

  label {
    font-size: 14px;
    font-weight: 700;
    color: #fff;
    background-color: #409eff;
    display: inline-block;
    padding: 10px;
    border-radius: 4px;
    margin: 10px 0;
    cursor: pointer;
    width: 150px;
  }

  label:hover {
    opacity: 0.8;
  }
}

.form {
  display: flex;
  justify-content: space-between;

  .left, .right {
    width: 49%;

    .inputfile {
      width: 0.1px;
      height: 0.1px;
      opacity: 0;
      overflow: hidden;
      position: absolute;
      z-index: -1;
    }
  }
}
</style>

